package com.github.jspxnet.worktask.core.job;

import com.github.jspxnet.boot.EnvFactory;
import com.github.jspxnet.json.JSONObject;
import com.github.jspxnet.sioc.BeanFactory;
import com.github.jspxnet.utils.BeanUtil;
import com.github.jspxnet.utils.ClassUtil;
import com.github.jspxnet.utils.StringUtil;
import com.github.jspxnet.worktask.model.enums.WorkTaskEnumType;
import com.github.jspxnet.worktask.table.ConfFlowNode;
import com.github.jspxnet.worktask.table.WorkTask;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.List;

/**
 * java 类对象调用
 * 建一个 class java执行任务调用,
 *
 */
@Slf4j
public class ClassJobTask extends BaseTaskAction{
    @Override
    public boolean execute() throws Exception {
        Object nodeIdObj = null;
        String className = confFlowJob.getClassName();
        String callMethod = confFlowJob.getCallMethod();
        if (!StringUtil.isNull(className) && !StringUtil.isNull(callMethod))
        {
            if (className.contains(StringUtil.AT))
            {
                BeanFactory beanFactory = EnvFactory.getBeanFactory();
                Object classObj = beanFactory.getBean(className);
                if (classObj==null)
                {
                    log.error("不能找到配置的ioc对象:{}",className);
                    return false;
                }
            } else
            {
                Object classObj = ClassUtil.loadClass(className).newInstance();
                nodeIdObj = BeanUtil.invoke(classObj, callMethod, new Object[]{currentWorkTask});
            }
        }

        //
        boolean runNext = false;
        if (nodeIdObj != null) {
            currentWorkTask.setWorkTaskType(WorkTaskEnumType.ClassJob.getValue());

            List<ConfFlowNode> nextNodeList = confWorkFlowDAO.getNextList(currentWorkTask.getFlowNo(), currentWorkTask.getNamespace(), currentWorkTask.getNodeId());

            for (ConfFlowNode confFlowNode : nextNodeList) {
                if (nodeIdObj.equals(confFlowNode.getNodeId())) {
                    //不做任何事情,直接到下一节点
                    WorkTask workTask = BeanUtil.copy(workTaskParam, WorkTask.class);
                    workTask.setNodeId(confFlowNode.getNodeId());
                    workTask.setCreateDate(new Date());
                    workTask.setUsers(workTaskParam.getUsers());
                    runtimeServiceDAO.save(workTask);
                    runNext = true;
                    //继续到指定的节点
                }
            }
        }
        //如果没有运行过到下一节点
        return !runNext;
    }
}